/**
 *
 * @version 1.0
 * @Author ady
 * @Date 2021/8/12 16:05
 */
import {
    getMachDictDateList,
    getMachmaintainAdd,
    getMachmaintainEdit,
    getMachmaintainFileCheck,
    getDevicemaintainList,
} from '@/api/keep'
import { format } from "@/sever/utils.js";

export const machSysInit = {
    data() {
        return {
            options: {
                disabledDate(date) {
                    return date > Date.now();
                }
            },
            machList: [],
            itemList: [],
            payList: [],
            machId: '',
            payNumList: [],
            fileList: [],
            uploadUrl: "",
            temporaryUrl:"",//临时路径
            docData: {
                key: "ms/hwctest/doc/file/2/",
                policy: "",
                ossaccessKeyId: "",
                success_action_status: "200", //让服务端返回200,不然，默认会返回204
                signature: "",
                dir: "ms/hwctest/doc/file/2/",
                host: this.$Global.fileSite,
                'x-oss-object-acl': 'public-read'
            },
            percentage: 0, //进度条
            percentText: "", //文件名字
            activeName:'0',
            radio:"1",
            tableList:['数量','单价','总价','备注',],
            numMap:{},
        }
    },
    watch:{
        activeName(val,oldval){
            this.tableList = ['数量','单价','总价','备注',];
            let list = [];
            this.tableNum = ['','','','',];
            let flag ;
            this.payList.forEach(i=>{
                if(val == i.code){
                    flag = i.flag;
                    list = [...i.remark,...this.tableList];
                }
                i['details'] = list;
            })
            if(flag){
                this.radio = '1';
            } else {
                this.radio = '2';
            }
        },
    },
    methods: {
        changeInput() {
            for (let i in this.numMap) {
                let str = 0;
                if (this.numMap[i].length > 0) {
                    for (let j = 0; j < this.numMap[i].length; j++) {
                        if (this.numMap[i][j][this.numMap[i][j].length - 4] == '' || this.numMap[i][j][this.numMap[i][j].length - 3] == '') {
                            this.numMap[i][j][this.numMap[i][j].length - 2] == "";
                        } else {
                            this.numMap[i][j][this.numMap[i][j].length - 2] = this.numMap[i][j][this.numMap[i][j].length - 4] * this.numMap[i][j][this.numMap[i][j].length - 3];
                        }
                        str +=this.numMap[i][j][this.numMap[i][j].length - 2];
                    }
                    this.payNumList[i] = str;
                }
            }
            this.$forceUpdate();
        },
        getMachList() {
            let params = {
                deptId: this.deptId,
            }
            getDevicemaintainList(params).then(res => {
                if (res.code == 200) {
                    this.machList = res.data.list;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        addRemark(index){
            let arr =[];
            for(let i = 0; i <this.payList[index].details.length; i++) {
                  arr.push('');
            };
            this.$nextTick(function (){
                this.$set(this.numMap[index],this.numMap[index].length,arr);
            })
            this.$forceUpdate();
        },
        removeRemark(index,j){
           this.numMap[index].splice(j,1);
           this.$forceUpdate();
        },
        getDateList(code) {
            let params = {
                deptId: this.deptId,
                dictCode: code,
            }
            getMachDictDateList(params).then(res => {
                if (res.code == 200) {
                    if (code == 'maintain_item') {
                        this.itemList = res.data.list;
                    } else if (code == 'maintain_pay') {
                        this.payList = res.data.list;
                        this.payList.forEach((i,index)=>{
                            if(i.remark) {
                                i['flag'] = true;
                                i.remark = (i.remark).split(',');
                                i['details'] = [...i.remark,...this.tableList];;
                            } else {
                                i['flag'] = false;
                            }
                            i['code'] = index.toString();
                        })
                        for(let i = 0; i<this.payList.length; i++) {
                            this.payNumList[i] = 0;
                            this.numMap[i] = [];
                        }
                        if(this.payList[0].flag) {
                            this.radio = '1';
                        } else {
                            this.radio = '2';
                        }
                        this.getAllList();
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error)
            })
        },
        doProgress(event, file, fileList) {
            if (this.uploadUrl != "") {
                this.percentage = parseInt(event.percent.toFixed(0));
                if (event.percent == 100) {
                    this.percentage = 0;
                }
            }
        },
        docSuccess(res, file) {
            if (this.uploadUrl != "") {
                if (file.status == "success") {
                    this.$Message.success("上传成功！");
                    this.fileList.push(this.temporaryUrl);
                }
            }
        },
        docError() {
            if (this.uploadUrl != "") {
                this.$Message.warning("上传失败！");
            }
        },
        removeFile(item, index) {
            this.fileList.splice(index, 1);
        },
        async beforeFile(file) {
            let params = {};
            this.docData = {};
            this.uploadUrl = "";
            this.temporaryUrl=""
            params.name = file.name;
            this.percentText = file.name;
            let reponses = await getMachmaintainFileCheck(params).then((res) => {
                if (res.code == 200) {
                    this.uploadUrl = res.data.host;
                    this.temporaryUrl = res.data.host + '/' + res.data.dir + '/' + res.data.fileName;
                    // setTimeout(() => {
                    //     this.fileList.push(url);
                    // }, 1000);
                    this.docData = {
                        key: res.data.dir + '/' + res.data.fileName,
                        policy: res.data.policy,
                        OSSAccessKeyId: res.data.accessId,
                        success_action_status: "200", //让服务端返回200,不然，默认会返回204
                        signature: res.data.signature,
                        dir: res.data.dir,
                        host: res.data.host,
                        // callback: res.data.callback,
                        "Content-Disposition": "attachment;filename=" + encodeURIComponent(file.name),
                        'x-oss-object-acl': 'public-read'
                    };
                    return true;
                } else {
                    this.$Message.warning(res.msg);
                    return false;
                }
            }).catch((error) => {
                console.log(error);
            });
            return reponses;
        },
        submitAll() {
            if (this.machId == '') {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择维修保养设备"
                });
                return;
            }
            if (this.maintainDate == '') {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择维修保养时间"
                });
                return;
            }
            if (this.workHour == '' && this.workMile == '') {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请输入工作里程或工作小时"
                });
                return;
            }
            if (this.checkedItemList.length == 0) {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择维修保养项目"
                });
                return;
            }
            let flag = false;
            for (let i = 0; i < this.payNumList.length; i++) {
                if (this.payNumList[i] != 0) {
                    flag = true;
                    break;
                }
            }
            /* if (!flag) {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请输入维修保养费用"
                });
                return;
            }
            for (let i in this.numMap) {
                if (this.numMap[i].length > 0) {
                    for (let j = 0; j < this.numMap[i].length; j++) {
                        if(this.numMap[i][j][0] == ""){
                            this.$Modal.warning({
                                title: "您有必填字段",
                                content: "请填写维修保养明细名称"
                            });
                            return;
                        }
                        if(this.numMap[i][j][this.numMap[i][j].length-4] == "") {
                            this.$Modal.warning({
                                title: "您有必填字段",
                                content: "请填写维修保养明细数量"
                            });
                            return;
                        }
                        if(this.numMap[i][j][this.numMap[i][j].length-3] == "") {
                            this.$Modal.warning({
                                title: "您有必填字段",
                                content: "请填写维修保养明细价格"
                            });
                            return;
                        }
                    }
                }
            } */
            if (this.maintainRemark == '') {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请输入维修保养说明"
                });
                return;
            }
            if (this.fileList.length == 0) {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请上传保养文件"
                });
                return;
            }
            let machCode, machTypeName;
            let payList = [];
            for (let i = 0; i < this.machList.length; i++) {
                if (this.machId == this.machList[i].machId) {
                    machTypeName = this.machList[i].machTypeName;
                    machCode = this.machList[i].machCode;
                }
            }
            for(let i = 0; i <this.payList.length; i++){
                let obj = {
                    payId: this.payList[i].id,
                    payName: this.payList[i].name,
                    payValue: this.payNumList[i],
                    detail: this.numMap[i].length > 0 ? JSON.stringify(this.numMap[i])  : '',
                }
                payList.push(obj)
            }
            // for (let i = 0; i < this.payNumList.length; i++) {
            //     let obj = {
            //         payId: this.payList[i].id || this.payList[i].payId,
            //         payName: this.payList[i].name || this.payList[i].payName,
            //         payValue: this.payNumList[i]
            //     }
            //     payList.push(obj);
            // }
            let itemList = [];
            for (let i = 0; i < this.checkedItemList.length; i++) {
                for (let j = 0; j < this.itemList.length; j++) {
                    if (this.itemList[j].id == this.checkedItemList[i]) {
                        let obj = {
                            itemId: this.itemList[j].id,
                            itemName: this.itemList[j].name,
                        }
                        itemList.push(obj)
                    }
                }
            }
            let filelist = [];
            // this.fileList.forEach(i => {
            //     filelist.push(i.url)
            // })
            if (this.isAdd) {
                let params = {
                    maintainId: this.maintainId,
                    deptId: this.deptId,
                    machId: this.machId,
                    machCode: machCode,
                    machTypeName: machTypeName,
                    maintainDate: format(this.maintainDate, "YYYY-MM-DD"),
                    workMile: this.workMile,
                    workHour: this.workHour,
                    itemList: itemList,
                    payList: payList,
                    maintainRemark: this.maintainRemark,
                    fileList: this.fileList,
                }
                getMachmaintainEdit(params).then(res => {
                    if (res.code == 200) {
                        // this.isAdd = false;
                        this.details();
                        this.$Message.success("操作成功");
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch(error => {
                    console.log(error)
                })
            } else {
                let params = {
                    deptId: this.deptId,
                    machId: this.machId,
                    machCode: machCode,
                    machTypeName: machTypeName,
                    maintainDate: format(this.maintainDate, "YYYY-MM-DD"),
                    workMile: this.workMile,
                    workHour: this.workHour,
                    itemList: itemList,
                    payList: payList,
                    maintainRemark: this.maintainRemark,
                    fileList: this.fileList,
                }
                getMachmaintainAdd(params).then(res => {
                    if (res.code == 200) {
                        this.addModal = false;
                        this.$Message.success("操作成功");
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                }).catch(error => {
                    console.log(error)
                })
            }
        },
    }
}
